package com.liu.netty.demo.client;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.SocketAddress;
import java.util.Arrays;

/**
 * @program: https://www.joinsunsoft.com
 * @description:
 * @author: LiuYong
 * @email: david.liu@ginghan.com
 * @create: 2022/3/22 21:24
 */

@Slf4j
public class EchoByteArrayChannelHandler extends ChannelHandlerAdapter {


    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof HeartBeatServerHandler.CloseEvent){
            log.error("========== Receive Close Event {}", ((HeartBeatServerHandler.CloseEvent)evt).getCount());
        }
    }

    private String debugObjectInfo(Object obj){
        if(obj==null)
            return null;

        return String.format("%s %s", obj, obj.getClass());
    }

    SocketAddress remoteAddress;

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise)
            throws Exception {
        log.error("======== close : {}", ctx.channel().remoteAddress());
        super.close(ctx, promise);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.error("======== channelInactive {}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.error("======== channelActive {}", ctx.channel().remoteAddress());
        ctx.writeAndFlush("Welcome to "
                + InetAddress.getLocalHost().getHostName() + " service!\n");

        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        byte[] buf = (byte[])msg;

        int i = ByteUtils.bytes2Int(buf, 0,2);

        String txt = ByteUtils.byte2msg(buf, "UTF-8");

        log.error("======== channelRead : {}({}={})", txt, i+"", (buf.length-2)+"");

        String responseTxt = "Received your message ! "+  txt +" \n";

        // 返回客户端消息 - 我已经接收到了你的消息
        ctx.writeAndFlush(ByteUtils.msg2bytes(responseTxt, "UTF-8"));

    }

}
